{% extends "base.html" %}

{% block content %}
    <!-- 英雄区域 -->
    <section class="hero-section text-center">
        <div class="container">
            <h1>糖尿病视网膜病变检测系统</h1>
            <p>早期发现，及时治疗，保护您的视力健康</p>
        </div>
    </section>

    <!-- 预测功能区域 -->
    <section class="content-section bg-white">
        <div class="container">
            <h2 class="text-center">视网膜病变预测</h2>
            <div class="row">
                <div class="col-md-6 offset-md-3">
                    <div class="card p-5">
                        <!-- 患者信息提示 -->
                        <div class="mb-4 alert alert-info" role="alert">
                            <p class="mb-0">
                                <i class="fas fa-info-circle"></i> 检测前请先<a href="/patient_info" class="alert-link">输入患者信息</a>，以便保存完整的检测记录。
                            </p>
                        </div>
                        
                        <!-- 当前患者信息显示 -->
                        {% if current_patient %}
                        <div class="mb-4 alert alert-success" role="alert">
                            <p class="font-weight-bold mb-1">当前检测患者：</p>
                            <p><strong>患者姓名：</strong>{{ current_patient.patient_name }}</p>
                            <p><strong>患者编号：</strong>{{ current_patient.patient_number }}</p>
                            <p><strong>主治医生：</strong>{{ current_patient.doctor_name }}</p>
                            <div class="mt-2">
                                <a href="/clear_patient_info" class="btn btn-sm btn-danger">清除患者信息</a>
                            </div>
                        </div>
                        {% endif %}
                        
                        <!-- 选择方式 -->
                        <div class="mb-4">
                            <div class="btn-group w-100" role="group">
                                <button type="button" id="upload-btn" class="btn btn-primary">上传图像</button>
                                <button type="button" id="camera-btn" class="btn btn-secondary">使用摄像头</button>
                            </div>
                        </div>

                        <!-- 上传区域 -->
                        <div id="upload-area" class="mb-4">
                            <div class="input-group">
                                <input type="file" class="form-control" id="image-input" accept="image/*">
                                <button class="btn btn-primary" type="button" id="predict-upload-btn">预测</button>
                            </div>
                        </div>

                        <!-- 摄像头区域 -->
                        <div id="camera-area" class="mb-4" style="display: none;">
                            <div class="image-container">
                                <video id="video" autoplay></video>
                            </div>
                            <div class="camera-controls">
                                <button class="btn btn-primary" type="button" id="capture-btn">拍照</button>
                                <button class="btn btn-secondary" type="button" id="stop-camera-btn">关闭摄像头</button>
                            </div>
                        </div>

                        <!-- 图像预览区域 -->
                        <div class="image-container text-center">
                            <img id="preview-image" src="" alt="预览图像">
                        </div>

                        <!-- 加载动画 -->
                        <div class="loading-spinner"></div>

                        <!-- 预测结果区域 -->
                        <div id="result-container" class="result-container text-center">
                            <div id="result-icon" class="result-icon"></div>
                            <h3 id="result-message"></h3>
                            <p id="result-confidence"></p>
                            <p id="result-disclaimer" class="text-muted text-sm mt-2"><i class="fas fa-info-circle"></i> 检测结果仅作为参考依据，最终结果请听从医生建议</p>
                            <!-- 置信度柱状图 -->
                            <div class="chart-container mt-4" style="height:250px;">
                                <canvas id="confidence-chart"></canvas>
                            </div>
                            <!-- 病人建议提示框 -->
                            <div id="patient-advice" class="mt-4 p-4 rounded bg-info text-white"></div>
                            <button class="btn btn-primary mt-3" type="button" id="reset-btn">重新开始</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 糖尿病简介区域 -->
    <section class="content-section">
        <div class="container">
            <h2 class="text-center">糖尿病简介</h2>
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <div class="card p-5">
                        <p>糖尿病是一种常见的慢性代谢性疾病，其主要特征是血糖水平长期高于正常范围。根据国际糖尿病联盟的数据，全球约有4.63亿糖尿病患者，预计到2045年这一数字将达到7亿。</p>
                        <p>糖尿病视网膜病变是糖尿病最常见的微血管并发症之一，也是导致成年人失明的主要原因。早期发现和治疗可以有效减少视力丧失的风险。</p>
                        <div class="mt-4">
                            <a href="/about" class="btn btn-primary">了解更多</a>
                            <a href="/dangers" class="btn btn-secondary">查看糖尿病危害</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 预防措施简介区域 -->
    <section class="content-section bg-white">
        <div class="container">
            <h2 class="text-center">预防措施</h2>
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <div class="card p-5">
                        <p>预防糖尿病及其并发症需要从生活方式、饮食习惯、定期体检等多个方面入手。通过科学的预防措施，可以有效降低糖尿病的发病风险，延缓病情进展。</p>
                        <div class="mt-4">
                            <a href="/prevention" class="btn btn-primary">查看详细预防措施</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
{% endblock %}

{% block scripts %}
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // 全局变量
        let stream = null;
        let confidenceChart = null;
        const video = document.getElementById('video');
        const previewImage = document.getElementById('preview-image');
        const uploadBtn = document.getElementById('upload-btn');
        const cameraBtn = document.getElementById('camera-btn');
        const uploadArea = document.getElementById('upload-area');
        const cameraArea = document.getElementById('camera-area');
        const cameraControls = document.querySelector('.camera-controls');
        const imageInput = document.getElementById('image-input');
        const predictUploadBtn = document.getElementById('predict-upload-btn');
        const captureBtn = document.getElementById('capture-btn');
        const stopCameraBtn = document.getElementById('stop-camera-btn');
        const loadingSpinner = document.querySelector('.loading-spinner');
        const resultContainer = document.getElementById('result-container');
        const resultIcon = document.getElementById('result-icon');
        const resultMessage = document.getElementById('result-message');
        const resultConfidence = document.getElementById('result-confidence');
        const patientAdvice = document.getElementById('patient-advice');
        const resetBtn = document.getElementById('reset-btn');

        // 切换上传方式
        uploadBtn.addEventListener('click', function() {
            uploadBtn.classList.add('btn-primary');
            uploadBtn.classList.remove('btn-secondary');
            cameraBtn.classList.add('btn-secondary');
            cameraBtn.classList.remove('btn-primary');
            uploadArea.style.display = 'block';
            cameraArea.style.display = 'none';
            cameraControls.style.display = 'none';
            previewImage.style.display = 'none';
            video.style.display = 'none';
            resultContainer.style.display = 'none';
            stopCamera();
        });

        cameraBtn.addEventListener('click', function() {
            cameraBtn.classList.add('btn-primary');
            cameraBtn.classList.remove('btn-secondary');
            uploadBtn.classList.add('btn-secondary');
            uploadBtn.classList.remove('btn-primary');
            uploadArea.style.display = 'none';
            cameraArea.style.display = 'block';
            cameraControls.style.display = 'block';
            previewImage.style.display = 'none';
            resultContainer.style.display = 'none';
            startCamera();
        });

        // 图像文件选择预览
        imageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    previewImage.src = event.target.result;
                    previewImage.style.display = 'block';
                    resultContainer.style.display = 'none';
                }
                reader.readAsDataURL(e.target.files[0]);
            }
        });

        // 上传图像预测
        predictUploadBtn.addEventListener('click', function() {
            if (imageInput.files && imageInput.files[0]) {
                const formData = new FormData();
                formData.append('image', imageInput.files[0]);
                predictWithImage(formData);
            } else {
                alert('请先选择一张图像');
            }
        });

        // 开始摄像头
        function startCamera() {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(function(mediaStream) {
                        stream = mediaStream;
                        video.srcObject = stream;
                        video.style.display = 'block';
                    })
                    .catch(function(err) {
                        console.error('无法访问摄像头:', err);
                        alert('无法访问摄像头，请确保您的设备有摄像头并已授予权限');
                    });
            } else {
                alert('您的浏览器不支持摄像头功能');
            }
        }

        // 停止摄像头
        function stopCamera() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                stream = null;
                video.srcObject = null;
                video.style.display = 'none';
            }
        }

        // 捕获图像
        captureBtn.addEventListener('click', function() {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            // 显示捕获的图像
            previewImage.src = canvas.toDataURL('image/png');
            previewImage.style.display = 'block';
            video.style.display = 'none';

            // 将图像数据发送到服务器进行预测
            const imageData = canvas.toDataURL('image/png');
            predictWithCamera(imageData);
        });

        // 关闭摄像头
        stopCameraBtn.addEventListener('click', function() {
            stopCamera();
            previewImage.style.display = 'none';
        });

        // 上传图像预测函数
        function predictWithImage(formData) {
            showLoading();

            fetch('/predict', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                showResult(data);
            })
            .catch(error => {
                hideLoading();
                console.error('预测失败:', error);
                alert('预测失败，请重试');
            });
        }

        // 摄像头图像预测函数
        function predictWithCamera(imageData) {
            showLoading();

            fetch('/predict_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ image: imageData })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                showResult(data);
            })
            .catch(error => {
                hideLoading();
                console.error('预测失败:', error);
                alert('预测失败，请重试');
            });
        }

        // 显示加载动画
        function showLoading() {
            loadingSpinner.style.display = 'block';
            resultContainer.style.display = 'none';
        }

        // 隐藏加载动画
        function hideLoading() {
            loadingSpinner.style.display = 'none';
        }

        // 显示预测结果
        function showResult(data) {
            if (data.error) {
                alert(data.error);
                return;
            }
            
            resultContainer.style.display = 'block';
            
            // 根据诊断结果设置样式和图标
            if (data.diagnosis === "正常") {
                resultContainer.classList.add('result-negative');
                resultContainer.classList.remove('result-positive');
                resultIcon.className = 'result-icon fas fa-check-circle';
            } else {
                resultContainer.classList.add('result-positive');
                resultContainer.classList.remove('result-negative');
                resultIcon.className = 'result-icon fas fa-exclamation-triangle';
            }
            
            // 显示诊断结果
            resultMessage.textContent = `预测结果：${data.diagnosis}`;
            
            // 显示置信度
            resultConfidence.textContent = `置信度：${(data.confidence * 100).toFixed(2)}%`;
            
            // 根据不同的诊断结果提供相应的健康建议
            provideAdvice(data.diagnosis);
            
            // 创建或更新置信度柱状图
            createConfidenceChart(data.all_probs);
        }
        
        // 根据诊断结果提供建议
        function provideAdvice(diagnosis) {
            let adviceHTML = '';
            
            switch(diagnosis) {
                case '正常':
                    adviceHTML = 
                        '<h4><i class="fas fa-heartbeat"></i> 健康建议</h4>' +
                        '<ul class="text-left mt-2">' +
                        '<li>继续保持良好的生活习惯和血糖控制</li>' +
                        '<li>定期进行眼部检查，建议每年至少一次</li>' +
                        '<li>注意均衡饮食，适量运动</li>' +
                        '<li>如有视力变化，请及时就医</li>' +
                        '</ul>';
                    break;
                case '轻度非增值性视网膜病变':
                    adviceHTML = 
                        '<h4><i class="fas fa-stethoscope"></i> 医生建议</h4>' +
                        '<ul class="text-left mt-2">' +
                        '<li>定期到眼科医生处进行随访检查</li>' +
                        '<li>严格控制血糖、血压和血脂水平</li>' +
                        '<li>保持健康的生活方式，包括均衡饮食和适量运动</li>' +
                        '<li>建议每6个月进行一次眼底检查</li>' +
                        '</ul>';
                    break;
                case '中度非增值性视网膜病变':
                    adviceHTML = 
                        '<h4><i class="fas fa-stethoscope"></i> 医生建议</h4>' +
                        '<ul class="text-left mt-2">' +
                        '<li>请尽快到眼科医生处进行详细检查</li>' +
                        '<li>严格控制血糖、血压和血脂，遵循医嘱进行治疗</li>' +
                        '<li>保持健康的生活方式，戒烟限酒</li>' +
                        '<li>建议每3-4个月进行一次眼底检查</li>' +
                        '<li>根据医生建议考虑激光治疗或其他干预措施</li>' +
                        '</ul>';
                    break;
                case '重度非增值性视网膜病变':
                    adviceHTML = 
                        '<h4><i class="fas fa-stethoscope"></i> 医生建议</h4>' +
                        '<ul class="text-left mt-2">' +
                        '<li>立即预约眼科专家进行详细检查</li>' +
                        '<li>严格控制血糖、血压和血脂，可能需要调整治疗方案</li>' +
                        '<li>避免剧烈运动和重体力劳动</li>' +
                        '<li>根据医生建议尽快进行激光光凝治疗</li>' +
                        '<li>建议每2-3个月进行一次眼底检查</li>' +
                        '</ul>';
                    break;
                case '增值性视网膜病变':
                    adviceHTML = 
                        '<h4><i class="fas fa-stethoscope"></i> 紧急建议</h4>' +
                        '<ul class="text-left mt-2">' +
                        '<li>立即前往医院眼科就诊，这是紧急情况</li>' +
                        '<li>严格控制血糖、血压和血脂</li>' +
                        '<li>避免剧烈运动和可能导致眼压升高的活动</li>' +
                        '<li>根据医生建议可能需要进行激光治疗或玻璃体切割手术</li>' +
                        '<li>术后需要密切随访，按照医生要求定期复查</li>' +
                        '</ul>';
                    break;
            }
            
            patientAdvice.innerHTML = adviceHTML;
        }

        // 创建置信度柱状图
        function createConfidenceChart(probabilities) {
            const ctx = document.getElementById('confidence-chart').getContext('2d');
            
            // 定义5种糖尿病视网膜病变等级
            const diseaseClasses = [
                "正常",
                "轻度非增值性视网膜病变",
                "中度非增值性视网膜病变",
                "重度非增值性视网膜病变",
                "增值性视网膜病变"
            ];
            
            // 如果已有图表实例，先销毁
            if (confidenceChart) {
                confidenceChart.destroy();
            }
            
            // 计算每个类别的置信度百分比
            const confidences = probabilities.map(prob => prob * 100);
            
            // 找出最高概率的索引
            const maxIndex = confidences.indexOf(Math.max(...confidences));
            
            // 创建颜色数组，高亮显示最高概率的类别
            const backgroundColors = confidences.map((_, index) => 
                index === maxIndex ? 'rgba(220, 53, 69, 0.7)' : 'rgba(108, 117, 125, 0.5)'
            );
            
            const borderColors = confidences.map((_, index) => 
                index === maxIndex ? 'rgba(220, 53, 69, 1)' : 'rgba(108, 117, 125, 1)'
            );
            
            // 创建新图表
            confidenceChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: diseaseClasses,
                    datasets: [{
                        label: '置信度 (%)',
                        data: confidences,
                        backgroundColor: backgroundColors,
                        borderColor: borderColors,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                callback: function(value) {
                                    return value + '%';
                                }
                            }
                        },
                        x: {
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45,
                                callback: function(value, index) {
                                    // 对于长标签，我们可以截断或使用更短的显示名称
                                    const labels = [
                                        "正常",
                                        "轻度病变",
                                        "中度病变",
                                        "重度病变",
                                        "增值性病变"
                                    ];
                                    return labels[index];
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `置信度: ${context.parsed.y.toFixed(2)}%`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // 重置按钮
        resetBtn.addEventListener('click', function() {
            resultContainer.style.display = 'none';
            previewImage.style.display = 'none';
            imageInput.value = '';
            if (uploadArea.style.display === 'block') {
                // 如果当前是上传模式，保持上传模式
            } else {
                // 如果当前是摄像头模式，重新启动摄像头
                video.style.display = 'block';
                previewImage.style.display = 'none';
                startCamera();
            }
        });
    </script>
{% endblock %}